<template>
  <div>
    <el-input :value="$route.query.roleName" :disabled="true"></el-input>

    <el-tree
      :data="roleAuthArr"
      ref="tree"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="selectArr"
      :props="defaultProps"
      @check-change="handleCheckChange"
    >
    </el-tree>

    <el-button type="primary" @click="save" :loading="loading">保存</el-button>
    <el-button type="primary" @click="$router.replace({ name: 'Role' })"
      >取消</el-button
    >
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleAuthArr: [],
      defaultProps: {
        label: "name",
      },
      selectArr: [],
      loading: false,
    };
  },
  mounted() {
    this.getRoleAuth();
  },
  methods: {
    //根据id获取权限
    async getRoleAuth() {
      let res = await this.$http.role.reqRoleAuth(this.$route.params.id);
      this.roleAuthArr = res.data.children;
      this.selectArr = this.getCheckedAuth(this.roleAuthArr);
    },
    handleCheckChange(v) {
      // console.log(v);
    },
    getCheckedAuth(allAuth, init = []) {
      return allAuth.reduce((pre, item) => {
        if (item.select && item.level == 4) {
          pre.push(item.id);
        } else {
          this.getCheckedAuth(item.children, init);
        }
        return pre;
      }, init);
    },
    async save() {
      this.loading = true;
      let selectArr = this.$refs.tree.getCheckedKeys();
      await this.$http.role.reqAssign(
        this.$route.params.id,
        selectArr.toString()
      );
      this.loading = false;
      const roleName = this.$route.query.roleName;
      const roles = this.$store.getters.roles;
      this.$message.success("分配成功");
      this.$router.replace("/acl/role/list", () => {
        if (roles.includes(roleName)) {
          window.location.reload();
        }
      });
    },
  },
};
</script>

<style>
</style>